<template>
  <div class="commodityManage auditCmpt">
    <!-- 查询表单 -->
    <div class="form-baseinfo">
      <LPSearchBar
        v-model="searchModel"
        :search-data="searchData"
        label-width="100px"
        @handleSearchSubmit="handleSearchSubmit"
        @handleSearchReset="handleSearchReset"
        @handleSelectChange="handleSelectChange"
      />
    </div>
    <div class="form-baseinfo">
      <div class="btn_area">
        <el-button size="small" type="primary" @click="syncProduct">同步产品</el-button>
        <el-button
          v-hasPermi="['LaborProtection.Products.Create']"
          size="medium"
          type="primary"
          @click="insertCommodity"
          >新增</el-button
        >
      </div>
      <!-- 表格列表 -->
      <LPTablePage
        :show-index="false"
        :show-indexfixed="false"
        index-label="顺序"
        :table-data="tableData"
        :table-column="tableColumn"
        :total="total"
        :current-page="currentPage"
        align="center"
        class="table"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
        <template slot="imgPath" slot-scope="{ row }">
          <div v-if="row.imagesList && row.imagesList.length > 0">
            <div v-if="row.imagesList[0].imgesUrl == null">暂无图片</div>
            <el-image
              v-else
              style="width: 100px; height: 100px"
              :src="row.imagesList[0].imgesUrl"
              fit="cover"
              :preview-src-list="srcList"
              @click="vbs(row.imagesList[0].imgesUrl)"
            />
          </div>
          <div v-else>暂无图片</div>
        </template>

        <template slot="cz" slot-scope="{ row }">
          <el-button v-hasPermi="['LaborProtection.Products']" type="text" @click="handColumnClick(row, 'detail')">
            详情
          </el-button>
          <el-button
            v-if="row.status === 0 || row.status === 1"
            v-hasPermi="['LaborProtection.Products.Update']"
            type="text"
            @click="handColumnClick(row, 'edit')"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.status === 0 || row.status === 1"
            v-hasPermi="['LaborProtection.Products.UpAndDown']"
            type="text"
            @click="handColumnClick(row, 'unWithdraw')"
          >
            上架
          </el-button>
          <el-button v-if="row.status === 2" type="text" @click="handColumnClick(row, 'withdraw')"> 下架 </el-button>
        </template>
      </LPTablePage>
    </div>
  </div>
</template>

<script>
import {
  getCategoryInfo,
  getIdCategoryInfo,
  getCategoryInfoList,
  updateCategoryInfo
} from '@/api/LaborProtection/categoryInfo'
import { AutoGetMARA, AutoExecMARA, AutoGetPrice, AutoExecPrice } from '@/api/LaborProtection/inventory'
import LPTablePage from '@/components/LPTablePage/index.vue'
import LPSearchBar from '@/components/LPSearchBar/index.vue'

export default {
  name: 'CommodityManage',
  components: { LPSearchBar, LPTablePage },
  data() {
    return {
      searchModel: {},
      searchData: [
        { label: '', placeholder: '物料简称', prop: 'cName' },
        {
          label: '',
          placeholder: '物料所属中类',
          prop: 'centre',
          type: 'select',
          event: 'true',
          option: []
        },
        {
          label: '',
          placeholder: '物料所属小类',
          prop: 'small',
          type: 'select',
          option: []
        },
        {
          label: '',
          placeholder: '上架状态',
          prop: 'status',
          type: 'select',
          option: [
            { label: '待上架', value: 0 },
            { label: '已上架', value: 2 },
            { label: '已下架', value: 1 }
          ]
        }
      ],
      // 列表数据
      tableData: [],
      // 表格字段
      tableColumn: [
        { label: '商品图片', prop: 'imgPath', render: true },
        { label: '商品简称', prop: 'cName' },
        { label: '物料中类', prop: 'centreTypeName' },
        { label: '物料小类', prop: 'smallTypeName' },
        // { label: "单位", prop: "receiveAddress" },
        { label: '状态', prop: 'statusName' },
        { label: '修改日期', prop: 'modifyTime' },
        { label: '操作', prop: 'cz', render: true, width: '150' }
      ],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      bigType: [],
      centreType: [],
      smallType: [],
      srcList: [],
      // 详情是否弹窗
      dialogVisible: false
    }
  },
  mounted() {
    this.getList()
    this.getCategoryInfo(2)
  },
  methods: {
    vbs(url) {
      this.srcList.push(url)
    },
    setDropDownStructure(maps) {
      return maps.map((item) => {
        return {
          label: item.cName,
          value: item.categoryNo
        }
      })
    },

    /**
     *  1：大类 2：中类 3：小类
     * @param {*} type
     */
    getCategoryInfo(type, parentId) {
      const data = {
        CCLass: type
      }
      if (parentId) {
        data.parentId = parentId
      }
      getCategoryInfo(data).then((res) => {
        if (!res.error) {
          if (type == 1) {
            this.bigType = res.items
          } else if (type == 2) {
            this.centreType = this.setDropDownStructure(res.items)
          } else {
            this.smallType = this.setDropDownStructure(res.items)
          }
        }
        this.searchData.forEach((item) => {
          if (item.label == '物料所属中类') {
            item.option = this.centreType
          } else if (item.label == '物料所属小类') {
            item.option = this.smallType
          }
        })
      })
    },
    // 查询按钮
    handleSearchSubmit() {
      console.log(2)
      this.currentPage = 1
      this.getList()
    },
    // 重置按钮
    handleSearchReset() {
      this.handleSearchSubmit()
    },
    syncProduct() {
      const data = {}
      AutoGetMARA(data).then((productInfo) => {
        AutoExecMARA(data).then((handleProduct) => {
          AutoGetPrice(data).then((priceInfo) => {
            AutoExecPrice(data).then((handlePrice) => {
              this.$message.success('同步成功')
              this.getList
            })
          })
        })
      })
    },
    handleSelectChange() {
      if (typeof this.searchModel.small !== 'undefined') {
        this.searchModel.small = ''
      }
      this.getCategoryInfo(3, this.searchModel.centre)
    },
    // 获取列表
    getList() {
      console.log(this.searchModel)
      const params = {
        cName: this.searchModel.cName,
        status: this.searchModel.status,
        SkipCount: this.currentPage,
        MaxResultCount: this.pageSize
      }
      if (typeof this.searchModel.centre !== 'undefined') {
        params.QCategoryNo = this.searchModel.centre
      }

      if (typeof this.searchModel.small !== 'undefined') {
        params.QCategoryNo = this.searchModel.small
      }

      getCategoryInfoList(params).then((res) => {
        if (!res.error) {
          const tempList = res.items
          tempList.forEach((item) => {
            item.childList.forEach((bigType) => {
              bigType.childList.forEach((centreType) => {
                centreType.childList.forEach((smallType) => {
                  item.smallTypeName = smallType.cName
                  item.centreTypeName = centreType.cName
                })
              })
            })
          })
          this.tableData = tempList
          this.total = res.totalCount
        }
      })
    },

    getByIdList(id) {
      getIdCategoryInfo(id).then((res) => {
        console.log(res)
      })
    },
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
      this.getList()
    },
    handleCurrentChange(v) {
      this.currentPage = v
      this.getList()
    },

    insertCommodity() {
      this.$router.push({
        path: './insert'
      })
    },
    handColumnClick(row, name) {
      if (name == 'detail') {
        this.$router.push({
          path: './detail',
          query: {
            id: row.id
          }
        })
      } else if (name == 'edit') {
        this.$router.push({
          path: './edit',
          query: {
            id: row.id
          }
        })
      } else if (name == 'withdraw') {
        this.$confirm('是否下架该商品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            updateCategoryInfo(row.id).then((res) => {
              if (!res.error) {
                this.$message({
                  type: 'success',
                  message: '下架成功!'
                })
                this.getList()
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消下架操作'
            })
          })
      } else if (name == 'unWithdraw') {
        updateCategoryInfo(row.id).then((res) => {
          if (!res.error) {
            this.$message({
              type: 'success',
              message: '上架成功!'
            })
            this.getList()
          }
        })
      }
    }
  }
}
</script>

<!-- <style lang="scss">
.el-form-item__label {
  font-weight: normal;
}

.el-dialog__body {
  padding-top: 0px;
}

.el-divider {
  margin-top: 5px;
}
</style> -->

<style lang="scss" scoped>
.auditCmpt {
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  .form-baseinfo:first-child {
    margin: 20px, 0, 20px, -10px;
    border-radius: 3px;
  }
  .form-baseinfo:last-child {
    background-color: #fff;
    .btn_area {
      padding: 0.2rem;
      border-top-left-radius: 3px;
      border-top-right-radius: 3px;
    }
  }
}

.commodityManage {
  .form-baseinfo {
    ::v-deep .search-bar input.el-input__inner {
      width: 2rem;
    }
  }

  ::v-deep .table {
    .red {
      color: $high_risk_color;
    }
  }
}
</style>
